package com.sm.honkon.ui.fragment.more

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import au.com.safie.user.app.util.CacheUtil
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.R
import com.sm.honkon.app.base.BaseFragment
import com.sm.honkon.app.event.ReadDataEvent
import com.sm.honkon.app.handle.BottomHandle
import com.sm.honkon.app.utils.CommondData
import com.sm.honkon.app.utils.SerialPortUtil
import com.sm.honkon.data.bean.CalibrationBean
import com.sm.honkon.data.bean.setMJAvg
import com.sm.honkon.databinding.FrgHandheldBinding
import com.sm.honkon.ui.adapter.CalibrationAdapter
import com.sm.honkon.ui.model.HandheldViewModel
import kotlinx.android.synthetic.main.frg_contro_log_cat.*
import kotlinx.android.synthetic.main.frg_handheld.*
import kotlinx.android.synthetic.main.frg_handheld.recycler_view
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class HandheldFragment : BaseFragment<HandheldViewModel, FrgHandheldBinding>() {
    override fun layoutId(): Int = R.layout.frg_handheld
    val adapter: CalibrationAdapter by lazy {
        CalibrationAdapter(updateData(mViewModel.selectMode.value)).apply {
            addChildClickViewIds(R.id.tv_jiaozhun, R.id.iv_reduce, R.id.iv_add, R.id.tv_test)
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.tv_jiaozhun -> {
                        this.selectPosition = position
                    }
                    R.id.tv_test -> {
                        if (this.selectTestPosition == position) {
                            stopTest()
                        } else {
                            startTest()
                        }
                        this.selectTestPosition = position
                    }
                    R.id.iv_reduce -> {
                        getItem(position).apply {
                            if (vol > mViewModel.config.minVoltage.get()) {
                                vol -= 5
                                if ((position in 1 until data.lastIndex).not()) {
                                    setMJAvg(data)
                                    notifyDataSetChanged()
                                } else
                                    notifyItemChanged(position)
                            }
                        }
                    }
                    R.id.iv_add -> {
                        getItem(position).apply {
                            if (vol < mViewModel.config.maxVoltage.get()) {
                                vol += 5
                                if ((position in 1 until data.lastIndex).not()) {
                                    setMJAvg(data)
                                    notifyDataSetChanged()
                                } else
                                    notifyItemChanged(position)
                            }
                        }
                    }
                }
            }
        }
    }

    var launch: Job? = null

    private fun stopTest() {
        SerialPortUtil.sendSerialPort(CommondData.STOP_TEST)
    }

    private fun startTest() {
        stopTest()
        launch = lifecycleScope.launch(Dispatchers.Main) {
            showLoading("正在连接中,请耐心等候")
            delay(1000)
            SerialPortUtil.sendSerialPort(CommondData.START_TEST)
            delay(10_000)
            ToastUtils.showShort("连接超时")
            dismissLoading()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
    }

    override fun lazyLoadData() {
        mDatabind.model = mViewModel
        mDatabind.handle = BottomHandle(nav())
        recycler_view.adapter = adapter
    }

    override fun onPause() {
        super.onPause()
        CacheUtil.setCommonConfig(mViewModel.config)
    }

    private fun updateData(value: Int): ArrayList<CalibrationBean> {
        return when (value) {
            0 -> mViewModel.config.t01064List
            1 -> mViewModel.config.t0532List
            2 -> mViewModel.config.t21064List
            else -> mViewModel.config.t2532List
        }
    }

    override fun createObserver() {
        super.createObserver()

        mViewModel.selectMode.observe(this) {
            adapter.setNewInstance(updateData(it))
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDataRead(event: ReadDataEvent) {
        event.data.let {
            if (isVisible.not())
                return@let
            if (it[0].and(0xFF) != 0x01)
                return@let
            val type = it[1].and(0xFF)
            val result = it[3].and(0xff)
            when (type) {
                0xE1 -> {
                    dismissLoading()
                    when (result) {
                        0xE1 -> {
                            ToastUtils.showShort("下发出光模式")
                            SerialPortUtil.sendSerialPort(
                                CommondData.getInstance()
                                    .makeMode(mViewModel.config.getRealMode().toByte())
                            )
                        }
                        0x00 -> {
                            ToastUtils.showShort("连接失败")
                        }
                        0xE2 -> {
                            ToastUtils.showShort("连接断开")
                        }
                    }
                }
                0x33 -> {
                    ToastUtils.showShort("下发延时指令")
                    SerialPortUtil.sendSerialPort(
                        CommondData.getInstance().makeTime(
                            mViewModel.config.getRealTime(0),
                            mViewModel.config.getRealTime(1)
                        )
                    )

                }
                0x88 -> {
                    ToastUtils.showShort("设置放大电压")
                    SerialPortUtil.sendSerialPort(
                        CommondData.getInstance().makeVolt(
                            mViewModel.config.getRealVolt(
                                mViewModel.selectMode.value,
                                adapter.getItem(adapter.selectTestPosition).mJ
                            ),
                            mViewModel.config.getRealVolt(
                                mViewModel.selectMode.value,
                                adapter.getItem(adapter.selectTestPosition).mJ
                            )
                        )
                    )
                }
                0x22 -> {
                    ToastUtils.showShort("设置放大电压")
                    SerialPortUtil.sendSerialPort(
                        CommondData.getInstance()
                            .makeWave((mViewModel.selectMode.value % 2).inv().and(0x01).toByte())
                    )
                }
                0xdd -> {
                    ToastUtils.showShort("开预燃")
                    SerialPortUtil.sendSerialPort(CommondData.YU_RAN_START)
                }
                0x55 -> {
                    ToastUtils.showShort("预燃开启")
                }

            }
        }
    }

    override fun onDestroyView() {
        stopTest()
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }
}